//This is the server part of the socket udp.
//The first step is also to get a handle of socket

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h> 

#include<pthread.h>

#define SERV_PORT   3000
#define CLIENT_PORT 6000
#define CLIENT_IP "127.0.0.1"

void * thread_info()
{

	struct sockaddr_in  addr_client;
	int client_len;

	int recv_num;
	int send_num;
	
	int sock_fd;

	struct sockaddr_in  addr_serv;

	//get the handle of socket
	sock_fd = socket(AF_INET,SOCK_DGRAM,0);

	if(sock_fd < 0)
	{
        	perror("socket");
       		exit(1);
	}
	else
	{
	        printf("sock sucessful\n");
	}

	
	//init the server socket
	memset(&addr_serv,0,sizeof(struct sockaddr_in));
	addr_serv.sin_family = AF_INET;
	addr_serv.sin_port = htons(SERV_PORT);
	addr_serv.sin_addr.s_addr = htonl(INADDR_ANY);
	//init the client socket
	memset(&addr_client,0,sizeof(struct sockaddr_in));
	addr_client.sin_family=AF_INET;
	addr_client.sin_port=htons(CLIENT_PORT);

	addr_client.sin_addr.s_addr = inet_addr(CLIENT_IP);

	client_len = sizeof(struct sockaddr_in);
	//bind the port of socket and handle

	if(bind(sock_fd,(struct sockaddr *)&addr_serv,sizeof(struct sockaddr_in))<0 )
	{
        	perror("bind");
        	exit(1);
	}
	else
	{
        	printf("bind sucess\n");

	}
	
	char recv_buf[20];

	while(1)
	{
        printf("begin recv:\n");
        //receive the message of client
        recv_num = recvfrom(sock_fd,recv_buf,sizeof(recv_buf),0,(struct sockaddr *)&addr_client,&client_len);

        if(recv_num <  0)
        {
                printf("bad\n");
                perror("again recvfrom");
                exit(1);
        }
        else
        {
        recv_buf[recv_num]='\0';
        printf("recv sucess:%s\n",recv_buf);
        }
        printf("begin send:\n");
        send_num = sendto(sock_fd,recv_buf,recv_num,0,(struct sockaddr *)&addr_client,client_len);

        if(send_num < 0)
        {
	        perror("sendto");
                exit(1);
        }
        else
        {
                printf("send sucessful\n");
        }
	}
	close(sock_fd);
	return;
}

int main()
{
	pthread_t thread_id;
        int ret;

        ret=pthread_create(&thread_id,NULL,(void*)thread_info,NULL);

        if(ret==-1)
        {
                printf("can not create new thread\n");
        }

        while(1)
	{
	}

	return 0;
}
















